<template>
    <div>
        <n-space vertical :size="12">
            <n-space>
                <n-input v-model:value="state.query.keyword" type="text"
                         placeholder="搜索" :clearable="true"
                         @keyup.enter="getDataList"/>
                <n-button @click="getDataList" type="default" ghost>查询</n-button>
                <!--      <n-button @click="clearSorter" type="info">重置</n-button>-->
                <n-button @click="addHandle()" type="info" ghost>新增</n-button>
                <n-button @click="deleteBatchHandle()" type="error" ghost>删除</n-button>
            </n-space>

            <n-data-table
                size="medium"
                :columns="columns"
                :data="state.result"
                :pagination="pagination"
            />
        </n-space>
        <n-drawer v-model:show="show" :width="500" :close-on-esc="true" :mask-closable="false">
            <n-drawer-content>
                <template #header>
                    流水线定义
                </template>
                <!--                <PipelineForm :ref="formRef" :pipeline="formValue"/>-->
                <n-form
                    ref="formRef"
                    label-placement="left"
                    label-width="auto"
                    :model="formValue"
                    :rules="rules">
                    <!--                :size="medium"-->
                    <!--            >-->
                    <n-form-item label="名称" path="name">
                        <n-input v-model:value="formValue.name" placeholder="输入名称"/>
                    </n-form-item>

                    <n-form-item label="工作目录" path="workspace">
                        <n-input v-model:value="formValue.workspace" placeholder="工作目录" />
                    </n-form-item>
                    <n-form-item label="启用" path="enabled">
                        <n-switch v-model:value="formValue.enabled" disabled/>
                    </n-form-item>

                    <n-divider title-placement="left">源代码仓库配置</n-divider>
                    <n-form-item label="URL" path="git_clone_url">
                        <n-input v-model:value="formValue.git_clone_url" placeholder="源代码库URL"/>
                    </n-form-item>
                    <n-form-item label="用户" path="git_username">
                        <n-input v-model:value="formValue.git_username" placeholder="登录用户"/>
                    </n-form-item>
                    <n-form-item label="密码" path="git_password">
                        <n-input v-model:value="formValue.git_password" type="password" show-password-on="click"
                                 placeholder="登录密码"/>
                    </n-form-item>

                    <n-divider title-placement="left">源码编译</n-divider>
                    <n-form-item label="编译服务器" path="builder_id">
                        <n-select label-field="name" value-field="id" v-model:value="formValue.builder_id"
                                  :options="state.builders"/>
                    </n-form-item>
                    <n-form-item label="编译环境" path="compiler_id">
                        <n-select label-field="name" value-field="id" v-model:value="formValue.compiler_id"
                                  :options="state.compilers"/>
                    </n-form-item>

                    <n-divider title-placement="left">镜像生成</n-divider>
                    <n-form-item label="镜像仓库" path="repository_id">
                        <n-select label-field="name" value-field="id" v-model:value="formValue.repository_id"
                                  :options="state.repositories"/>
                    </n-form-item>
                    <n-form-item label="镜像命名空间" path="namespace">
                        <n-input v-model:value="formValue.namespace" placeholder="镜像命名空间"/>
                    </n-form-item>
                    <n-form-item label="镜像名称" path="image">
                        <n-input v-model:value="formValue.image" placeholder="镜像名称"/>
                    </n-form-item>
                    <n-form-item label="镜像版本" path="tag">
                        <n-input v-model:value="formValue.tag" placeholder="镜像版本" value="${timestamp}" readonly
                                 disabled/>
                        <!--                        <n-select label-field="name" value-field="id" v-model:value="formValue.tag"-->
                        <!--                                  :options="state.deployers"/>-->
                    </n-form-item>

                    <n-divider title-placement="left">应用部署</n-divider>
                    <n-form-item label="部署服务器" path="deployer_id">
                        <n-select label-field="name" value-field="id" v-model:value="formValue.deployer_id"
                                  :options="state.deployers"/>
                    </n-form-item>
                    <n-form-item label="容器端口" path="source_port">
<!--                        <n-input v-model:value="formValue.source_port" placeholder="容器端口" value=""/>-->
                        <n-input-number v-model:value="formValue.source_port" clearable :show-button="false" placeholder="容器端口"/>
                    </n-form-item>
                    <n-form-item label="暴露端口" path="target_port">
<!--                        <n-input v-model:value="formValue.target_port" placeholder="暴露端口" value=""/>-->
                        <n-input-number v-model:value="formValue.target_port" clearable :show-button="false" placeholder="暴露端口"/>
                    </n-form-item>

                </n-form>
                <template #footer>
                    <n-flex justify="space-between" style="width: 100%">
                        <n-button @click="cancelClicked" ghost type="error">
                            关闭
                        </n-button>
                        <n-button @click="saveClicked" ghost type="primary">
                            保存
                        </n-button>
                    </n-flex>
                </template>
            </n-drawer-content>
        </n-drawer>
        <!--        <n-drawer v-model:show="showVariable" :width="500" :close-on-esc="true" :mask-closable="false">-->
        <!--            <n-drawer-content>-->
        <!--                <template #header>-->
        <!--                    流水线定义-->
        <!--                </template>-->
        <!--                <VariableForm ref="variableFormRef" :pipelineId="formValue.id"/>-->
        <!--                <template #footer>-->
        <!--                    <n-flex justify="space-between" style="width: 100%">-->
        <!--                        <n-button @click="cancelClicked" ghost type="error">-->
        <!--                            关闭-->
        <!--                        </n-button>-->
        <!--                        <n-button @click="saveClicked" ghost type="primary">-->
        <!--                            保存-->
        <!--                        </n-button>-->
        <!--                    </n-flex>-->
        <!--                </template>-->
        <!--            </n-drawer-content>-->

        <!--        </n-drawer>-->
    </div>
</template>

<script setup lang="ts">
import {type FormInst, NButton, NPopconfirm, NSwitch} from 'naive-ui'
import {h, onMounted, reactive, ref} from "vue";
import {
    deletePipeline,
    getPipelineById,
    getPipelineList,
    savePipeline,
    switchPipelineEnabled,
    updatePipeline
} from "@/api/pm/pipeline.ts";
import {getCompilerList} from "@/api/sm/compiler.ts";
import {getBuilderList} from "@/api/sm/builder.ts";
import {getRepositoryList} from "@/api/sm/repository.ts";
import {getDeployerList} from "@/api/sm/deployer.ts";
import {useSseStore} from "@/stores";

const sseStore = useSseStore()
const state = reactive({
    query: {
        keyword: ''
    },
    compilers: [],
    builders: [],
    deployers: [],
    repositories: [],
    result: [],

    selectedCompiler: ref(null),
    selectedBuilder: ref(null),
    selectedDeployer: ref(null),
    selectedRepository: ref(null),
})

let editType = "new"
const show = ref(false)
const formRef = ref<FormInst | null>(null)
const formValue = ref({
    id: '',
    name: '',
    workspace: '',
    enabled: true,
    git_clone_url: '',
    git_username: '',
    git_password: '',
    namespace: '',
    image: '',
    tag: '${timestamp}',
    commands: '',
    compiler_id: '',
    deployer_id: '',
    builder_id: '',
    repository_id: '',
    source_port: 0,
    target_port: 0,
})
const rules = {
    name: {
        required: true,
        message: '姓名不能为空',
        trigger: ['input', 'blur']
    },
    git_clone_url: {
        required: true,
        message: '源代码库 URL 不能为空',
        trigger: ['input', 'blur']
    },
}

const columns = [
    // {
    //     title: '-',
    //     key: 'idx',
    //     align: "center",
    //     textAlign: "center",
    //     width: 60,
    //     render(row, index) {
    //         return h(
    //             "span",
    //             {
    //                 style: {"color": "gray"}
    //             },
    //             index + 1);
    //     },
    // },
    {
        title: '启用',
        key: 'enabled',
        width: 60,
        render(row) {
            return h(
                NSwitch,
                {
                    value: row.enabled, size: 'small', onUpdateValue: () => {
                        switchPipelineEnabled(row.id)
                        row.enabled = !row.enabled
                        if(row.enabled){
                            window.$message?.success('已启用流水线 ['+row.name+']')
                        } else {
                            window.$message?.info('已禁用流水线 ['+row.name+']')
                        }
                    }
                }
            )
        },
    },
    {
        title: '名称',
        key: 'name',
        minWidth: 150
    },
    {
        title: '源代码库URL',
        key: 'git_clone_url',
    },
    {
        title: '工作目录',
        key: 'workspace',
    },
    {
        title: '镜像命名空间',
        key: 'namespace',
    },
    {
        title: '镜像名称',
        key: 'image',
    },
    {
        title: '镜像版本',
        key: 'tag',
    },
    {
        title: '操作',
        key: 'action',
        width: 200,
        align: "right",
        titleAlign: 'right',
        fixed: 'right',
        render(row) {
            return [
                h(NPopconfirm,
                    {
                        positiveButtonProps: {
                            ghost: true,
                            bordered: true,
                            size: 'tiny',
                            type: 'error',
                        },
                        negativeButtonProps: {
                            ghost: true,
                            bordered: true,
                            size: 'tiny',
                        },
                        onPositiveClick: () => {
                            deletePipeline(row.id).then((res: any) => {
                                if (res.code != 200) {
                                    window.$message?.error(res.message)
                                } else {
                                    window.$message?.success(res.message)
                                    console.log(res.message)
                                    getDataList();
                                }
                            })
                        },
                        negativeText: "取消",
                        positiveText: "删除"
                    },
                    {
                        trigger: () => {
                            return h(
                                NButton,
                                {
                                    size: 'small',
                                    style: {
                                        marginLeft: '3px'
                                    },
                                    ghost: true,
                                    type: "error",
                                    bordered: true,
                                    tooltip: '删除',
                                },
                                {default: () => '删除'}
                            )
                        },
                        default: () => {
                            return '确认删除【' + row.name + '】？'
                        }
                    }
                ),
                h(NButton,
                    {
                        size: 'small',
                        style: {
                            marginLeft: '3px'
                        },
                        ghost: true,
                        type: "info",
                        bordered: true,
                        tooltip: "编辑",
                        onClick: () => {
                            getPipelineById(row.id).then((res: any) => {
                                formValue.value = res.data
                                console.log(formValue.value)
                            })
                            editType = "edit"
                            show.value = true
                        }
                    },
                    {default: () => "编辑"}
                ),
            ]
        }
    }
]


const pagination = {
    pageSize: 10
}

const getDataList = () => {
    getPipelineList().then(res => {
        state.result = res.data
        console.log(state.result)
    })
    getCompilerList().then(res => {
        state.compilers = res.data
        console.log(state.compilers)
    })
    getBuilderList().then(res => {
        state.builders = res.data
        console.log(state.builders)
    })
    getRepositoryList().then(res => {
        state.repositories = res.data
        console.log(state.repositories)
    })
    getDeployerList().then(res => {
        state.deployers = res.data
        console.log(state.deployers)
    })
}
// 新增
const addHandle = () => {
    formValue.value = {
        id: '',
        name: '',
        workspace: '',
        enabled: true,
        git_clone_url: '',
        git_username: '',
        git_password: '',
        namespace: '',
        image: '',
        tag: '${timestamp}',
        commands: '',
        compiler_id: '',
        deployer_id: '',
        builder_id: '',
        repository_id: '',
        source_port: 0,
        target_port: 0,
    }
    editType = "new"
    show.value = true
}

const deleteBatchHandle = () => {
    window.$message?.error('点击了删除')
}

const cancelClicked = (e: MouseEvent) => {
    show.value = false
}

const saveClicked = (e: MouseEvent) => {
    e.preventDefault()
    window.$message?.info('点击了保存')
    window.$message?.info(formValue.value.toString())
    console.log(formValue.value)
    // window.$message?.info(formRef.value)
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (editType == "new") {
                savePipeline(formValue.value).then((res: any) => {
                    if (res.code != 200) {
                        window.$message?.error(res.message)
                    } else {
                        window.$message?.success("保存成功")
                        console.log(res.message)
                        show.value = false;
                        getDataList();
                    }
                })
            } else {
                updatePipeline(formValue.value).then((res: any) => {
                    if (res.code != 200) {
                        window.$message?.error(res.message)
                    } else {
                        window.$message?.success(res.message)
                        console.log(res.message)
                        show.value = false;
                        getDataList();
                    }
                })
            }
        } else {
            console.log(errors.map((e) => e.message))
            window.$message?.error(errors.map((e) => e.message))
        }
    })
}

const renderLabel = (option) => {
    return `${option.name} [${option.ip}]`
}

onMounted(() => {
    getDataList()
})


</script>

<style></style>
